/**
 * @desc
 * @author wangXi
 * @date 2016/1/6
 */
require(['jquery', 'wxi'], function ($, w) {
    var wrap=$('.wrap-monitor:first'),
        ele_body=wrap.find('tbody');

    var ajax_prefix ='/home/ajax_handle';

    var rental_kiosk_list={};

    //填写了teamviwer账号的租赁机id
    var k_list=[];

    ele_body.empty();

    //TODO array unique, do not override prototype
    Array.prototype.getUnique = function () {
        var u = {}, a = [];
        for (var i = 0, l = this.length; i < l; ++i) {
            if (u.hasOwnProperty(this[i])) {
                continue;
            }
            a.push(this[i]);
            u[this[i]] = 1;
        }
        return a;
    };

    var label_kiosk_with_teamvwr=function(){
        k_list.length && ele_body.find('tr').each(function(dx){
            if( _.indexOf(k_list, $(this).children('td:first').text()) !== -1 ){
                $(this).find('td.btn-grp>.btn-teamvwr>i').addClass('green');
            }
        });
    };

    //fetch monitor data
    var fetch_monitor_data= function () {

        var _render_nodes=function(d){
            if(d.success){
                if(d.result && d.result.length){
                    var res= d.result,
                        htm='',
                        html_rows={},
                        seq=['kiosk_id', 'kiosk_addr', 'kiosk_ip', 'connected',
                            'cpu_usage', 'memory_usage', 'disk_free_size',
                            'net_total_recv_bytes', 'net_total_send_bytes',
                            'udm_controller_started', 'udm_rental_started',
                            'ubx_version', 'last_sync_time', 'last_boot_time'
                        ];

                    //非正常的设备排在前面，依据kiosk_id升序
                    var kiosk_ids=[],
                        bad_kiosk_ids=[];

                    w.map(res, function (item) {
                        var row=[],
                            kid=item['kiosk_id'];
                        item['kiosk_addr']=(kid in rental_kiosk_list && rental_kiosk_list[kid]['address'])
                            || '<span class="red">未填写</span>';
                        kiosk_ids.push(kid);

                        if(item['connected']==0){
                            bad_kiosk_ids.push(kid);

                            //连接超时, 除kiosk_id外其它数据显示为 --
                            w.map(seq, function (key) {
                                var shown_items=['kiosk_id', 'kiosk_addr', 'kiosk_ip',
                                    'last_sync_time', 'last_boot_time', 'ubx_version'];

                                if(item.hasOwnProperty(key)){
                                    if( shown_items.indexOf(key) == -1){
                                        item[key]='--';
                                    }

                                    if(key == 'connected'){
                                        item[key]='<i class="fa fa-close red"' +
                                            ' data-toggle="tooltip" title="网络中断或监控停止"></i>';
                                    }

                                    if(key!= 'net_total_recv_bytes' && key!='net_total_send_bytes'){
                                        row.push('<td>'+item[key]+'</td>');
                                    }
                                    else{
                                        row.push(item[key]);
                                    }

                                }
                            });

                        }
                        else{
                            w.map(seq, function (key) {
                                var v=item[key];

                                if(item['udm_controller_started'] == 0 || item['udm_rental_started']==0){
                                    bad_kiosk_ids.push(item['kiosk_id']);
                                }

                                if(key=='connected'){
                                    v = '<i class="fa fa-check-circle green" data-toggle="tooltip" title="已连接"></i>';
                                }
                                else if(key=='cpu_usage' || key=='memory_usage'){
                                    v = parseInt(v)+'%';
                                }
                                else if(key=='disk_free_size'){
                                    v=parseFloat(v/1024/1024/1024).toFixed(2)+'GB';
                                }
                                else if(key=='net_total_recv_bytes'){
                                    v= '下载<span class="net_card_label">'+parseFloat(v/1024).toFixed(2)+'MB</span><br>';
                                }
                                else if(key=='net_total_send_bytes'){
                                    v= '上传<span class="net_card_label">'+parseFloat(v/1024).toFixed(2)+'MB</span>';
                                }
                                else if(key=='udm_rental_started' || key=='udm_controller_started'){
                                    v = v==0 ?
                                        '<i class="fa fa-ban red" data-toggle="tooltip" title="未启动"></i>':
                                        '<i class="fa fa-circle green" data-toggle="tooltip" title="已启动"></i>';
                                }

                                if(key!= 'net_total_recv_bytes' && key!='net_total_send_bytes'){
                                    row.push('<td>'+v+'</td>');
                                }
                                else{
                                    row.push(v);
                                }

                            });
                        }

                        var idx1=seq.indexOf('net_total_recv_bytes'),
                            idx2=seq.indexOf('net_total_send_bytes');
                        row.splice(idx1, 2, '<td>'+ [row[idx1], row[idx2]].join(' ') + '</td>');

                        var btn_grp = '<td class="btn-grp">' +
                            '<a class="btn-teamvwr" data-toggle="tooltip" title="Teamviewer账号">' +
                            '<i class="fa fa-desktop"></i></a>'+
                            '<a class="btn-show-log" data-toggle="tooltip" title="查看维护日志">' +
                            '<i class="fa fa-file-o"></i></a>'+
                            '<a class="btn-add-log" data-toggle="tooltip" title="添加维护日志">' +
                            '<i class="fa fa-bullhorn"></i></a>'+
                            '</td>';

                        html_rows[kid]='<tr>'+row.join('')+btn_grp+'</tr>';
                    });

                    //将出现异常的租赁机优先排在前面
                    var sort_num=function(a,b){
                        return parseInt(a) - parseInt(b);
                    };

                    bad_kiosk_ids=bad_kiosk_ids.getUnique().sort(sort_num);

                    var intersec_ids=[];
                    w.map(kiosk_ids, function (_id) {
                        if(bad_kiosk_ids.indexOf(_id) == -1){
                            intersec_ids.push(_id);
                        }
                    });
                    intersec_ids.getUnique().sort(sort_num);

                    var arr=[bad_kiosk_ids.join(), intersec_ids.join()].join().split(',');
                    if(arr.length>1 && arr[arr.length-1]==''){
                        arr.splice(-1, 1);
                    }

                    arr=arr.getUnique();
                    w.map(arr, function (id) {
                        htm += html_rows[''+id];
                    });

                    ele_body.html(htm);

                    //summary kiosk list
                    $('#summary-kiosk').html('<p style="font-size:14px;color:#567;border-bottom:1px dashed #aaa;">' +
                        '<i class="fa fa-info-circle"></i> 共'
                        +kiosk_ids.length+'台机器, <i class="fa fa-circle green"></i> 正常运行'
                        +(kiosk_ids.length-bad_kiosk_ids.length)+'台, <i class="fa fa-circle red"></i> 故障'
                        +bad_kiosk_ids.length+'台</p>');
                }
                else{
                    w.util.tipMsg('', '未查询到监控数据')
                }
            }
            else{
                w.util.tipMsg('', '获取数据错误:'+ d.info);
                location.reload(true);
            }
        };

        if(!Object.getOwnPropertyNames(rental_kiosk_list).length){
            //get rental kiosk list
            $.ajax({
                url: ajax_prefix,
                data: {op: 'get_rental_kiosk_list'},
                dataType: 'json',
                async: false,
                timeout: 3000,
                success: function(d){
                    if(d.result && d.result.length){
                        _.each(d.result, function(row){
                            rental_kiosk_list[row.kiosk_id]=row;
                        });
                    }
                    //console.log(rental_kiosk_list);
                },
                error: function(xhr, errTxt){
                    console.log(errTxt);
                }
            });
        }

        w.util.loadContent(ele_body, function (cb) {
            $.get(ajax_prefix, {op:'get_kiosk_status'}, function (d) {
                _render_nodes(d);

                label_kiosk_with_teamvwr();

            }, 'json');

            typeof cb=='function' && cb();
        });

    };



    //page first load
    fetch_monitor_data();

    //on prod env, uncomment follow
    var monitor_interval=5000;
    var timer_monitor=setInterval(function(){
        fetch_monitor_data();
    }, monitor_interval);

    //attach btn event
    $('body').on('click', 'tbody .btn-grp>a', function(e){
        var that=$(this),
            idx=$(this).index(),
            accept_action=['teamvwr', 'show-log', 'add-log'],
            ele_tr = $(this).parents('tr'),
            kiosk_id=parseInt(ele_tr.children('td:first').text()),
            act=accept_action[idx],
            title_prefix='kiosk-'+kiosk_id+':';

        if(act == 'teamvwr'){
            //查看teamviewer账号
            var wrap=$('#wx-md-wrap > div.md-edit');
            var orig_id='', orig_pwd='';

            wxi.ui.modal({
                title: title_prefix+'TeamViewer账号',
                msg: wrap.html(),
                height:130,
                is_shown: function(targ){
                    $.get(ajax_prefix, {op:'op_teamvwr', kiosk_id: kiosk_id}, function(d){
                        if(d.success){
                            var res= d.result,
                                t_id=res['teamvwr_id'] || '',
                                t_pass=res['teamvwr_pwd'] || '';
                            orig_id=t_id;
                            orig_pwd=t_pass;

                            targ.find('input[name=teamv_id]').val(t_id);
                            targ.find('input[name=teamv_pwd]').val(t_pass);
                        }

                    }, 'json');
                },
                cb: function(ok_btn, modal){
                    var fm_data=wxi.util.preCheckForm(modal.find('form'));

                    if( (orig_id=='' && orig_pwd =='') &&
                        (fm_data.teamv_id=='' || fm_data.teamv_pwd=='')){
                        wxi.util.tipMsg('','初始ID, 密码不允许为空');
                        return false;
                    }

                    if(fm_data.teamv_id == orig_id && fm_data.teamv_pwd == orig_pwd){
                        wxi.util.tipMsg('','数据未修改');
                        return false;
                    }

                    $.post(ajax_prefix, {op:'op_teamvwr', kiosk_id: kiosk_id, data:fm_data}, function(d){
                        var tip= d.success ? '操作成功' :'操作失败:'+ d.info;
                        wxi.util.tipMsg('', tip, 1000, function(){
                            modal.find('button.close').trigger('click');
                            if(fm_data.teamv_id==''){
                                that.children('i').removeClass('green');
                                var idx=k_list.indexOf(kiosk_id);
                                if( idx > -1){
                                    k_list.splice(idx, 1);
                                }
                            }
                            else{
                                k_list.push(kiosk_id);
                                that.children('i').addClass('green');
                            }
                        });

                    }, 'json');

                }

            });
        }

        if(act == 'show-log'){
            //查看维护日志
            var wrap=$('#wx-md-wrap > div.md-show-log');
            wxi.ui.modal({
                title: title_prefix+'查看维护日志',
                msg: wrap.html(),
                height: 400,
                is_shown:function(targ){
                    $.get(ajax_prefix, {op:'op_memo_log', kiosk_id: kiosk_id}, function(d){
                        if(d.success){
                            var res= d.result, html='';

                            if(res.length>0){

                                _.each(res, function(item){
                                    html += '<div class="row log_item"><p>' +item.log_msg+ '</p>' +
                                            '<p class="pull-right log_label">'+
                                            item.log_author+' 上报于 '+item.log_time+'</p>'+
                                        '</div>\n';

                                });
                            }

                        targ.find('div.log_container').html(html);

                        }

                    }, 'json');
                },

                hide_foot: true
            });
        }

        if(act == 'add-log') {
            //添加一条维护记录
            wxi.ui.modal({
                title: title_prefix + '添加维护日志',
                msg: $('#wx-md-wrap > div.md-add-log').html(),
                height: 280,
                ok_txt: '提交',
                cb: function(ok_btn, modal){
                    var data=wxi.util.preCheckForm(modal.find('form'));
                    //var log_msg = wxi.string.trim(data.log_msg, ['\n','', '\t']);
                    var log_msg = $.trim(data.log_msg);
                    if(log_msg==''){
                        wxi.util.tipMsg('','请填写日志内容');
                        return false;
                    }

                    $.post(ajax_prefix, {op:'op_memo_log', kiosk_id: kiosk_id, data:{
                        log_msg: log_msg

                    }}, function(d){
                        var tip= d.success ? '添加成功' :'添加失败';
                        wxi.util.tipMsg('', tip, 600, function(){
                            modal.find('button.close').trigger('click');
                        });

                    }, 'json');

                }
            });
        }

    });

    //$('#btn-hide-kiosk').on('click', function(){
    //   //get not-in-use machine list
    //
    //});

    //对添加了teamviwer账号的机器标记颜色
    setTimeout(function(){
        $.get(ajax_prefix, {op: 'get_teamvwr_list'}, function(d){
            if(d.result.length){
                k_list=_.map(d.result, function(item){
                    return item['kiosk_id'];
                });

                label_kiosk_with_teamvwr();
            }

        }, 'json');

    }, 2000);

    
});
